class MapController < ApplicationController
  
  # TODO Tile based system for maps.
  # TODO Use RMagick to render map on edit complete.
  # TODO Create map editing features.
  
  before_filter :login_required
  
  def index
    redirect_to :action => "view"
  end
  
  def view
    @player = Player.find(session[:id])
    @map = Map.find(@player.map_id)
    @page_title = @map.name
  end
  
  def up
    @player = Player.find(session[:id])
    unless @player.ypos - 1 < 0
      @player.ypos -= 1
      @player.update
    else
      flash[:error] = "You can't leave the map!"
    end
    redirect_to :action => "view"
  end
  
  def left
    @player = Player.find(session[:id])
    unless @player.xpos - 1 < 0
      @player.xpos -= 1
      @player.update
    else
      flash[:error] = "You can't leave the map!"
    end
    redirect_to :action => "view"
  end
  
  def right
    @player = Player.find(session[:id])
    @map = Map.find(@player.map_id)
    unless @player.xpos + 2 > @map.width
      @player.xpos += 1
      @player.update
    else
      flash[:error] = "You can't leave the map!"
    end
    redirect_to :action => "view"
  end
  
  def down
    @player = Player.find(session[:id])
    @map = Map.find(@player.map_id)
    unless @player.ypos + 2 > @map.height
      @player.ypos += 1
      @player.update
    else
      flash[:error] = "You can't leave the map!"
    end
    redirect_to :action => "view"
  end
  
  def render_map
    if @user.rank == 2
      require 'RMagick'
      @player = Player.find(session[:id])
      @map = Map.find(@player.map_id)
      mapRender = Magick::ImageList.new
      @map.tiles.split(",").each do |i|
        tile = Magick::Image.read('public/images/tiles/' + i + '.png').first
        mapRender << tile
      end
      $width = @map.width.to_s
      $height = @map.height.to_s
      finalMap = mapRender.montage do
        self.geometry = "16x16+0+0"
        self.tile = $width + "x" + $height
      end
      finalMap.write('public/images/maps/' + @map.id.to_s + '.png')
      redirect_to :action => "view"
    else
      flash[:error] = "You need to be an administrator to do that."
      redirect_to :controller => "site", :action => "index"
    end
  end
end
